<!DOCTYPE html>
<meta charset="utf-8">
<meta name="timeout" content="long">
<title>Screen wake locks respect page visibility changes</title>
<link rel="help" href="https://w3c.github.io/screen-wake-lock/#handling-document-loss-of-visibility">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>

promise_test(async t => {
  const screenWakeLock = await navigator.wakeLock.request('screen');
  assert_false(screenWakeLock.released, "The released attribute is initially false")
  const screenWakeLockReleased =
      new EventWatcher(t, screenWakeLock, "release").wait_for("release");

  const eventWatcher = new EventWatcher(t, document, "visibilitychange");
  await eventWatcher.wait_for("visibilitychange");
  assert_true(document.hidden, "document is hidden after the visibilitychange event");
  await screenWakeLockReleased;
  assert_true(screenWakeLock.released, "The released attribute is true after the lock is released");
  await promise_rejects_dom(t, "NotAllowedError", navigator.wakeLock.request('screen'),
      "new screen locks are not allowed when the page is not visible");

  await eventWatcher.wait_for("visibilitychange");
  assert_false(document.hidden, "document is no longer hidden after the visibilitychange event");
}, "Test screen locks respect page visibility changes");

</script>

<p>Switch the page to the background, then switch back to it.</p>
